<template>
    <section>
        <div class="carryBroadcastTitle">
            制作{{ route.query.imgType === '001' ? '上刊' : '下刊' }}报告-检查照片<span
            >（<label>任务数量:</label>{{ photoNumber }}张,<label>完成数量:</label>{{ actualPhotoNumber }}张）</span
            >
        </div>
        <el-tabs v-model="type" class="tab-pane common-table-tabs" @tab-click="changeTab">
            <el-tab-pane :label="`有效照片(${photoNum})`" :name="1"> </el-tab-pane>
            <el-tab-pane :label="`失效照片(${invalidPhotoNum}张)`" :name="2"> </el-tab-pane>
        </el-tabs>
    </section>
    <section>
        <div class="formSearch">
            <el-form class="formSearch-form">
                <el-form-item>
                    <el-input v-model="formData.machineNum" placeholder="机器码">
                        <template #prefix>
                            <div class="label">
                                <el-icon :size="16">
                                    <Search />
                                </el-icon>
                            </div>
                        </template>
                    </el-input>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <el-button type="primary" @click="getChangeData"> 查询 </el-button>
                </el-form-item>
            </el-form>
            <el-checkbox v-model="specialPhotoFlag" @change="getChangeData">重拍照片</el-checkbox>
        </div>
        <section v-loading="carryBroadLoading">
            <div v-if="photoDataList.length">
                <span
                    v-for="(item, index) in photoDataList"
                    :key="item"
                    class="imageBox"
                    @mouseover="mouseoverImage(item)"
                    @mouseleave="mousemoveImage()"
                >
                    <el-image
                        style="width: 188px; height: 333px; border-radius: 4.76px; margin: 0 27px 30px 0"
                        :src="item.imgPath"
                        fit="cover"
                        lazy
                    />
                    <div v-if="currentImage === item.id" class="mask">
                        <section class="hanleViwe" @click="viweImg(item)">
                            <el-icon><FullScreen /></el-icon>
                            查看大图
                        </section>
                    </div>
                </span>
            </div>
            <template v-else>
                <el-empty image="https://puma-obs.xinchao.com/atprut/test/prut/2023/01/13/1673601926509.png" />
            </template>
        </section>
        <div class="dialog-image-visible">
            <el-dialog v-model="dialogImageVisible" :title="type === 1 ? '标记失效原因' : '取消失效原因'" align-center>
                <section class="imgBox">
                    <el-image :src="imgObj.imgPath" fit="cover" lazy />
                    <section v-if="type === 1" class="btnGroup">
                        <template v-for="(reasons, index) in listImageReasons" :key="index">
                            <span
                                :style="{ width: reasons.errorCode === '7' ? '220px' : '100px' }"
                                :class="
                                    reasonsList.map((mark) => mark.errorCode).includes(reasons.errorCode)
                                        ? 'active'
                                        : ''
                                "
                                @click="onMark(reasons)"
                            >
                                {{ reasons.remark }}
                            </span>
                        </template>
                    </section>
                    <section v-if="type === 2" class="btnGroup">
                        <template v-for="(reasons, index) in imgObj.reasons" :key="index" class="reasons">
                            <span :style="{ width: reasons.errorCode === '7' ? '220px' : '100px' }">
                                {{ reasons.remark }}
                                <el-icon @click="onCancelRemark(imgObj, reasons)"><Close /></el-icon>
                            </span>
                        </template>
                    </section>
                </section>
                <template #footer>
                    <el-row type="flex" justify="end">
                        <span class="dialog-footer">
                            <el-button @click="dialogImageVisible = false">取消</el-button>
                            <el-button v-if="type === 1" type="primary" @click="onMarkInvalid">标记失效</el-button>
                            <el-button v-if="type === 2" type="primary" @click="onCancelInvalid(imgObj)"
                                >取消失效</el-button
                            >
                        </span>
                    </el-row>
                </template>
            </el-dialog>
        </div>

        <section class="page">
            <Pagination
                :page-no="formData.pageNum"
                :page-size="formData.pageSize"
                :total="formData.total"
                @changePage="changePage"
                @changePageSize="changePageSize"
            ></Pagination>
        </section>
        <section class="btnHandel">
            <div>
                <el-button @click="onBackList">返回列表</el-button>
                <el-button @click="router.back()">返回上一步</el-button
                ><el-button type="primary" :loading="btnLoading" @click="makeReport">生成报告</el-button>
            </div>
        </section>
    </section>
</template>

<script setup lang="ts">
import { computed, reactive, ref, shallowRef, toRef, watch, defineAsyncComponent, onMounted } from 'vue';
import useTableSetting from '@/hooks/useTableSetting.ts';
import {
    photostat,
    invalidatePhoto,
    cancelReason,
    validatePhoto,
    photoList,
    invalidPhotoList,
    addReport,
} from '@/api/carryBroadcast';
import Pagination from '@/components/common/Pagination.vue';
import { useRouter, useRoute } from 'vue-router';
import type { TabsPaneContext } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listImageReasons } from '@/utils/config.ts';

const router = useRouter();
const route = useRoute();
import { useStore } from 'vuex';

const store = useStore();
const userInfo = computed(() => store.state.userGroup.userInfo);
const imgObj = reactive({});
const btnLoading = ref(false);
const carryBroadLoading = ref(null);
const imgLoading = ref(false);
const currentImage = ref(0);
const specialPhotoFlag = ref(false);
const formData = reactive({
    specialPhotoFlag: 0,
    city: userInfo.value.cityList[0].cityCode,
    machineNum: '',
    systemType: 1,
    planIds: [route.query.planId],
    pageSizeZero: false,
    imgType: route.query.imgType,
    pageNum: 1,
    pageSize: 10,
    total: 0,
});
const type = ref(1);
const photoDataList = ref([]);
const dialogImageVisible = ref(false);
const photoData = reactive({
    planId: route.query.planId, //	integer	必须1方案ID	mock: @integer
    mediaType: 1,
    imgType: route.query.imgType, // 001 上刊， 002 下刊
});
const photoNumber = ref(0);
const actualPhotoNumber = ref(0);
const listMark = ref([]);
const photoNum = ref(0);
const invalidPhotoNum = ref(0);
const reasonsList = ref([]);
onMounted(async () => {
    getData();
});
const getPhotostat = async () => {
    const { requriedPhotoNum, actualPhotoNum } = await photostat(photoData);
    photoNumber.value = requriedPhotoNum;
    actualPhotoNumber.value = actualPhotoNum;
};
const getPhotoList = async () => {
    formData.specialPhotoFlag = specialPhotoFlag.value ? 1 : 0;
    const { data, total } = await photoList(formData);
    photoDataList.value = data;
    formData.total = total;
    photoNum.value = total;
};
const getInvalidPhotoList = async () => {
    formData.specialPhotoFlag = specialPhotoFlag.value ? 1 : 0;
    const { data, total } = await invalidPhotoList(formData);
    photoDataList.value = data;
    formData.total = total;
    invalidPhotoNum.value = total;
};
const changeTab = async (tab: TabsPaneContext, event: Event) => {
    formData.pageNum = 1;
    formData.pageSize = 10;
    formData.machineNum = '';
    type.value = +tab.props.name;
    getChangeData();
};
const getChangeData = async () => {
    carryBroadLoading.value = true;
    try {
        if (type.value === 1) {
            await getPhotoList();
        } else {
            await getInvalidPhotoList();
        }
    } finally {
        carryBroadLoading.value = false;
    }
};
const getData = async () => {
    carryBroadLoading.value = true;
    formData.specialPhotoFlag = specialPhotoFlag.value ? 1 : 0;
    try {
        if (type.value === 1) {
            await getPhotoList();
            const { total } = await invalidPhotoList(formData);
            invalidPhotoNum.value = total;
            await getPhotostat();
        } else {
            await getInvalidPhotoList();
            const { total } = await photoList(formData);
            photoNum.value = total;
            await getPhotostat();
        }
    } finally {
        carryBroadLoading.value = false;
    }
};
const onMarkInvalid = async () => {
    if (reasonsList.value && reasonsList.value.length) {
        let params = {
            reasons: reasonsList.value,
            id: imgObj.id,
            systemType: 1,
            city: formData.city,
            reshoot_flag: specialPhotoFlag.value ? 1 : 0,
        };
        await invalidatePhoto(params);
        dialogImageVisible.value = false;
        getData();
    } else {
        ElMessage.error('至少有一个失效原因');
    }
};
const mouseoverImage = (item) => {
    currentImage.value = item.id;
};
const mousemoveImage = () => {
    currentImage.value = 0;
};
const onCancelInvalid = async (item) => {
    let params = { id: item.id, systemType: 1, city: formData.city, reshoot_flag: specialPhotoFlag.value ? 1 : 0 };
    await validatePhoto(params);
    dialogImageVisible.value = false;
    getData();
};
const onCancelRemark = async (item: object, reasons: object) => {
    let params = { reasons: reasons, id: item.id, systemType: 1, city: formData.city };
    await cancelReason(params);
    let index = item.reasons.findIndex((Mark: any) => Mark.errorCode === reasons.errorCode);
    item.reasons.splice(index, 1);
};
const viweImg = (item: any) => {
    Object.assign(imgObj, item);
    dialogImageVisible.value = true;
    reasonsList.value = [];
};
const errorCodeMark = computed(() => listMark.value.map((item) => item.errorCode));

const onMark = (reasons: any) => {
    let index = reasonsList.value.findIndex((Mark: any) => Mark.errorCode === reasons.errorCode);
    console.log(index);
    if (index > -1) {
        reasonsList.value.splice(index, 1);
    } else {
        reasonsList.value.push(reasons);
    }
    console.log(reasonsList.value);
};
const onConfirmMakeReport = async () => {
    let params = {
        reportType: route.query.imgType,
        planId: route.query.planId,
        mediaType: 1,
        frameImageUrl: route.query.url,
    };
    btnLoading.value = true;
    try {
        await addReport(params);
    } finally {
        btnLoading.value = false;
    }
    router.push({
        path: '/delivery/viewReport',
        query: { planId: route.query.planId, imgType: route.query.imgType },
    });
};
const makeReport = async () => {
    if (photoNumber.value > actualPhotoNumber.value) {
        try {
            ElMessageBox.confirm('照片数少于任务数，是否确定报告', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
            })
                .then(() => {
                    onConfirmMakeReport();
                })
                .catch(() => {});
        } finally {
        }
    } else {
        onConfirmMakeReport();
    }
};

const onBackList = () => {
    router.push({
        path: '/delivery/program',
    });
};
const changePage = (val) => {
    formData.pageNum = val;
    getData();
};
const changePageSize = (val) => {
    formData.pageSize = val;
    getData();
};
</script>

<style lang="scss" scoped>
.dialog-image-visible {
    ::v-deep .el-dialog {
        width: 30%;
        height: 70%;
        // height: auto;
    }
    ::v-deep .el-dialog__header {
        box-sizing: border-box;
        width: 100%;
        height: 10%;
        line-height: 10%;
    }
    ::v-deep .el-dialog__body {
        width: 100%;
        height: 80%;
        box-sizing: border-box;
    }
    ::v-deep .el-dialog__footer {
        width: 100%;
        line-height: 10%;
        height: 10%;
    }

    .imgBox {
        height: 100%;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        ::v-deep .el-image {
            margin: 0;
            height: 100%;
            width: auto;
            border-radius: 4.76px;
        }
    }
}

.carryBroadcastTitle {
    margin-bottom: 20px;
    color: #e60044;
    label {
        color: #a1a6af;
    }
}
.formSearch {
    display: flex;
    justify-content: space-between;
    :deep(.el-form-item__content) {
        display: flex;
        flex-wrap: nowrap;
    }
    .label {
        margin-top: 3px;
    }
}
.imageBox {
    display: inline-block;
    position: relative;
    .mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 188px;
        height: 333px;
        background-image: linear-gradient(
            180deg,
            rgba(0, 0, 0, 0) 0%,
            rgba(0, 0, 0, 0.59) 32%,
            rgba(0, 0, 0, 0.79) 100%
        );
        border-radius: 4.76px;
        display: flex;
        align-items: center;
        .hanleViwe {
            width: 188px;
            height: 29px;
            border-radius: 5px 5px 0 0;
            text-align: center;
            line-height: 29px;
            color: #fff;
            font-size: 12px;
            cursor: pointer;
        }
    }
}

.btnGroup {
    width: 245px;
    span {
        display: inline-block;
        text-align: center;
        color: #252525;
        background: #f5f5f5;
        margin: 0 10px 15px 10px;
        padding: 6px 0;
        width: 92px;
        border-radius: 2px;
        font-size: 12px;
        cursor: pointer;
    }
    .active {
        font-size: 12px;
        color: #e60044;
        background: rgba(230, 0, 68, 0.06);
    }
    .handelBtn {
        width: 72px;
        height: 28px;
        background: #e60044;
        border-radius: 4px;
        border: none;
    }
}
.btnHandel {
    height: 56px;
    background: #fff;
    padding-right: 16px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    position: absolute;
    right: 22px;
    left: 22px;
    bottom: 0;
    z-index: 9;
}
.page {
    margin-bottom: 45px;
}
</style>
